package com.practice.map遍历的几种方式;

import com.google.common.collect.Maps;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by IntelliJ IDEA2021.3
 * @Author: Tenghw
 * @Date: 2022/11/05  12:35
 * @Description:
 */
public class Demo1 {
    public static void main(String[] args) {
        HashMap<String, String> hashMap1 = Maps.newHashMap();
        hashMap1.put("江苏","南京");
        hashMap1.put("浙江","杭州");
        hashMap1.put("安徽","合肥");

        //遍历方式1：map.keySet()方法
        for(String key: hashMap1.keySet()){
            System.out.println("key="+key+", value="+hashMap1.get(key));
        }
        System.out.println("--------------------------------");
        //遍历方式2：map.values()方法; 缺点：只能遍历值，不能遍历键
        for(String value: hashMap1.values()){
            System.out.println("value="+value);
        }
        System.out.println("--------------------------------");
        //遍历方式3：map.entrySet()方法(推荐，尤其数据量大的情况下)
        for(Map.Entry<String,String>  entry  :  hashMap1.entrySet()){
            System.out.println("key="+entry.getKey()+", value="+entry.getValue());
        }
        System.out.println("--------------------------------");
        //遍历方式4：迭代器iterator()方法
        Iterator<Map.Entry<String, String>> iterator = hashMap1.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, String> entry = iterator.next();
            System.out.println("key="+entry.getKey()+", value="+entry.getValue());
        }
    }
}
